/**
 * 微信jssdk调用
 */

import {
	loginQmWx,
	loginShopWx,
	onWxParams
} from './api.js'
import Util from './util.js'
import Config from './config.js'
let wx = require("jweixin-module");
export default {
	async authorize(code,tag) {
		//获取token
		// let token = data.query.token || Util.getQueryVariable('token');
		//判断code是否存在
		let token = uni.getStorageSync("token");
		let result = null;
		code= code || Util.getQueryVariable('code');
		tag= tag || Util.getQueryVariable('tag');
		let localTag = uni.getStorageSync('shoptag');
		if (tag && localTag && tag !== localTag) {
			uni.removeStorageSync('token');
			uni.removeStorageSync('qmtoken');
			uni.setStorageSync("shoptag", tag);
			// 拉起微信授权
			this.setBackUrl();
		} else if (!token) {
			tag = this.getShopTag(tag);
			if (!code) {
				// 拉起微信授权
				this.setBackUrl();
			} else {
				if (code instanceof Array) {
					code = code[code.length - 1];
				}
				let res = await loginQmWx({
					auth_tag: 'WECHAT',
					code: code,
					tag: tag
				});
				let respo = res.data;
				if (respo.code == 0) {
					uni.setStorageSync("qmtoken", respo.data.qm_token);
					let respon = await loginShopWx({
						auth_tag: 'WECHAT',
						qm_token: respo.data.qm_token,
						tag: tag
					});
					let respons = respon.data;
					if (respons.code == 0) {
						console.log('授权成功=>' + respons.data.token);
						uni.setStorageSync("token", respons.data.token);
						location.reload();
					} else if (respons.code == -996) {
						this.setBackUrl(1, respons.data.app_id);
					} else {
						console.log('商家微信授权-异常报错=>' + JSON.stringify(respon));
					}


				} else {
					console.log('千马微信授权-异常报错=>' + JSON.stringify(res));
					// 拉起微信授权
					this.setBackUrl();
				}
			}
		} else {
			result = token;
		}
		return result;
	},
	// 商家入驻流程
	async posAuthorize(code) {
		code = code || Util.getQueryVariable('code');
		let qmtoken = uni.getStorageSync("qmtoken");
		let result = null;
		if (!qmtoken) {
			if (!code) {
				// 拉起微信授权
				this.setBackUrl();
			} else {
				console.log('code=>' + code);
				let res = await loginQmWx({
					auth_tag: 'WECHAT',
					code: code
				});
				let resp = res.data;
				console.log(resp);
				if (resp.code == 0) {
					uni.setStorageSync("qmtoken", resp.data.qm_token);
					let tok = uni.getStorageSync("qmtoken");
					if(tok){
						location.reload();
					}
					
				} else {
					// 拉起微信授权
					// this.setBackUrl();
				}
			}
		} else {
			result = qmtoken;
		}
		return result;
	},
	// 商家微信授权传参
	async setBackUrl(type, appId) {
		let tag = uni.getStorageSync('shoptag');
		let url = this.getAuthParamUrl();
		console.log('BackUrl=>' + url);
		uni.showLoading({
			title: "授权加载中..."
		});
		let res = await onWxParams({
			url,
			tag
		});
		let resp = res.data;
		console.log('<=onWxParams=>' + JSON.stringify(resp));
		if (resp.code == 0) {
			if (type == 1) {
				this.authOther(appId, resp.data.key);
			} else {
				this.authMe(resp.data.key);
			}
		}
	},
	getAuthParamUrl() {
		let hash = window.location.hash;
		let search = window.location.search
		if (!search) {
			if (hash.indexOf('?') != -1) {
				let hashs = hash.split('?');
				hash = hashs[0];
				search = hashs[1];
			}
		} else {
			if (search.indexOf('?') != -1) {
				search = search.replace('?', '');
			}
		}
		if (hash == '#/') {
			hash = '/pages/index/index/index'
		} else {
			hash = hash.replace('#/', '/');
		}
		let back_url = location.origin + '/#' + hash + '?back=' + encodeURIComponent(hash);
		let vars = search.split('&');
		for (let i = 0; i < vars.length; i++) {
			var pair = vars[i].split("=");
			if (vars[i].indexOf('state=') || vars[i].indexOf('code=')) {
				continue;
			}
			if (back_url.indexOf(vars[i]) === -1) {
				if (back_url.indexOf('?') != -1) {
					back_url += '&' + vars[i];
				} else {
					back_url += '?' + vars[i];
				}
			} else {
				console.log('不存在：' + vars[i])
			}
		}
		console.log("back=>" + back_url)

		let tag = uni.getStorageSync('shoptag');
		if (back_url.indexOf('tag=') == -1 && tag) {
			back_url += '&tag=' + tag;
		}

		let register_code = uni.getStorageSync('register_code')
		if (register_code) {
			back_url += '&promotion_code=' + register_code;
		}
		let qmtoken = uni.getStorageSync('qmtoken')
		if (qmtoken) {
			back_url += '&qm_token=' + qmtoken;
		}
		let sleId = uni.getStorageSync('sleId')
		if (sleId) {
			back_url += '&sleId=' + sleId;
		}
		return back_url;
	},
	subStrURL() {
		let path = location.hash;
		if (path.indexOf('?') > -1) {
			path = path.substring(0, path.indexOf('?'));
		} else if (path.indexOf('&') > -1) {
			path = path.substring(0, path.indexOf('&'));
		}
		return path;
	},
	getShopTag(tag) {
		let shoptag = tag;
		if (shoptag.indexOf('?tag=') > -1) {
			shoptag = shoptag.substr(shoptag.indexOf('?tag=') + 5);
		}
		shoptag && uni.setStorageSync("shoptag", shoptag);
		return shoptag;
	},
	checkAuth(data, context) {
		//获取token
		let token = data.query.token;
		token = token ? token : Util.getQueryVariable('token');
		console.log("平台token=》" + token)
		if (token) {
			uni.setStorageSync("token", token);
			uni.setStorage({
				key: 'token',
				data: token,
				success: function() {
					console.log('平台token');
				}
			})
		}
		let qmtoken = data.query.qmtoken;
		qmtoken = qmtoken ? qmtoken : Util.getQueryVariable('qmtoken');
		if (qmtoken) {
			uni.setStorageSync("qmtoken", qmtoken);
			uni.setStorage({
				key: 'qmtoken',
				data: qmtoken,
				success: function() {
					console.log('商家token');
				}
			})
		}

		this.onCheckToken(context, data);
	},
	onCheckToken(context, data) {
		//判断平台token是否存在

		let qmtoken = uni.getStorageSync('qmtoken');
		let that = this;
		if (!Util.isExist(qmtoken)) {
			uni.showLoading({
				title: "平台授权中..."
			})
			uni.getStorage({
				key: 'qmtoken',
				success: function(res) {
					if (!res.data) {
						qmtoken = res.data;
						that.checkCode(context, data)
					}
				},
				fail: function(res) {
					that.checkCode(context, data)
				}
			});
			return;
		}
		//检测商家token
		let token = uni.getStorageSync('token');
		if (!Util.isExist(token)) {
			uni.showLoading({
				title: "商家授权中..."
			})
			uni.getStorage({
				key: 'token',
				success: function(res) {
					if (!res.data) {
						that.authShopToken(context, qmtoken)
					}
				},
				fail: function(res) {
					that.authShopToken(context, qmtoken)
				}
			});
		}
	},
	/**
	 * 检测code是否存在
	 * @param {Object} context
	 */
	checkCode(context, data) {
		// #ifdef H5
		//判断code是否存在
		let code = data.query.code;
		code = code ? code : Util.getQueryVariable('code');
		let back = data.query.back;
		back = back ? back : Util.getQueryVariable('back');
		//如果都不存在，吊起微信授权
		if (!Util.isExist(code)) {
			this.onSaveParams(0);
		} else {
			let that = this;
			let tag = uni.getStorageSync('shoptag');
			loginQmWx({
				auth_tag: 'WECHAT',
				code: code,
				tag: tag
			}).then(res => {
				console.log("请求成功")
				let data = res.data;
				if (data.code == 0) {
					let qmtoken = data.data.qm_token;
					if (qmtoken) {
						context.$store.commit('platformLogin', qmtoken);
						that.authShopToken(context, qmtoken, data)
					} else {
						uni.hideLoading()
						console.log("未获取qmtoken")
					}

				}
			});
		}
		// #endif
	},
	/**
	 * 获取商家token,用户操作token
	 * 
	 * @param {Object} context
	 */
	authShopToken(context, qmtoken, global) {
		let tag = uni.getStorageSync('shoptag');
		let that = this;
		context.$store.commit('logout')
		loginShopWx({
			auth_tag: 'WECHAT',
			qm_token: qmtoken,
			tag: tag
		}).then(res => {
			let data = res.data;
			console.log(data)
			uni.hideLoading()
			if (data.code == 0) {
				uni.setStorageSync('token', data.data.token)
				uni.setStorage({
					key: 'token',
					data: data.data.token,
					success: (data) => {
						console.log("保存token成功")
						//Util.redirectTo('/pages/member/index/index');
					}
				});
				context.$store.commit('login', data.data);
				location.href = location.origin + '/' + location.hash;
			} else if (data.code == -10011) {
				if (data.data.key) {
					Util.redirectTo('/pages/login/bind/bind', {
						keyCode: data.data.key
					});
				}
			} else if (data.code == -996) {
				//未授权
				console.log("app_id：" + data.data.app_id)
				that.onSaveParams(1, data.data.app_id);
			}
		});
	},
	onSaveParams(type, app_id) {
		let hash = window.location.hash;
		let search = window.location.search
		if (!search) {
			if (hash.indexOf('?') != -1) {
				let hashs = hash.split('?');
				hash = hashs[0];
				search = hashs[1];
			}
		} else {
			if (search.indexOf('?') != -1) {
				search = search.replace('?', '');
			}
		}
		if (hash == '#/') {
			hash = '/pages/index/index/index'
		} else {
			hash = hash.replace('#/', '/');
		}
		let page = hash;
		let vars = search.split('&');
		for (let i = 0; i < vars.length; i++) {
			var pair = vars[i].split("=");
			if (pair[0] != 'tag' && vars[i].indexOf(pair[0]) == -1) {
				if (page.indexOf('?') != -1) {
					page += '&' + vars[i];
				} else {
					page += '?' + vars[i];
				}
			}
		}
		console.log("back=>" + page)
		let tag = uni.getStorageSync('shoptag');
		let back_url = Config.h5Domain + window.location.pathname + '#' + hash + '?back=' + encodeURIComponent(page) +
			'&tag=' + tag;
		let register_code = uni.getStorageSync('register_code')
		if (register_code) {
			back_url += '&promotion_code=' + register_code;
		}
		let qmtoken = uni.getStorageSync('qmtoken')
		if (qmtoken) {
			back_url += '&qm_token=' + qmtoken;
		}
		let identity = uni.getStorageSync('identity')
		if (identity) {
			url += '&selId=' + identity;
		}
		let params = {
			url: back_url,
			tag: tag
		}
		uni.showLoading({
			title: "授权加载中..."
		})
		onWxParams(params).then(res => {
			let data = res.data;
			console.log("key=>" + data.data.key);
			uni.hideLoading()
			if (data.code == 0) {
				if (type == 1) {
					this.authOther(app_id, data.data.key)
				} else {
					this.authMe(data.data.key)
				}
			}
		})
	},

	/**
	 * 商家授权
	 * @param {Object} appid 商家appid
	 * @param {Object} back_url 回调地址
	 */
	authOther(appid, back_url) {

		// let redirect_url = appid + '.mango.qianmabo.com' + '/api/wechat/open_authorize/back_url/' + encodeURIComponent(
		// 		back_url) + '/token/' +localStorage.getItem("qmtoken");
		let redirect_url = Config.baseUrl + '/api/wechat/open_authorize/back_url/' + encodeURIComponent(
			back_url) + '/token/' + localStorage.getItem("qmtoken");
		let component_appid = Config.appId;
		let uri = encodeURIComponent(redirect_url);
		let authURL =
			`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=STATE&component_appid=${component_appid}#wechat_redirect`;
		location.href = authURL;
	},
	/**
	 * 平台公众号授权
	 * @param {Object} back_url 回调地址
	 */
	authMe(back_url) {
		let redirect_url = Config.baseUrl + 'api/wechatauth/index?back_url=' + encodeURIComponent(back_url);
		let appid = "wxaccb99362d4e0e4f";
		let authURL =
			`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_url}&response_type=code&scope=snsapi_base&state=e54c849337a8948c5bbe0553bc9878e6&connect_redirect=1#wechat_redirect`;
		location.href = authURL;
	},
	/**
	 * 自动播放
	 * @param {Object} callback
	 */
	autoPlay(callback) {
		wx.config({
			// 配置信息, 即使不正确也能使用 wx.ready
			debug: false,
			appId: '',
			timestamp: 1,
			nonceStr: '',
			signature: '',
			jsApiList: []
		});
		wx.ready(function() {
			callback()
		});
	},
	/**
	 * 微信公众号jssdk授权
	 * @param {Object} params
	 */
	init(params) {
		console.log(params.signature)
		wx.config({
			debug: params.debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
			appId: params.appId, // 必填，公众号的唯一标识
			timestamp: params.timestamp, // 必填，生成签名的时间戳
			nonceStr: params.nonceStr, // 必填，生成签名的随机串
			signature: params.signature, // 必填，签名
			jsApiList: ['chooseWXPay', 'openAddress', 'updateAppMessageShareData', 'updateTimelineShareData'] // 必填，需要使用的JS接口列表
		});
	},
	/**
	 * 发起支付
	 * @param {Object} jsApiParame
	 * @param {Object} callback
	 */
	pay(jsApiParame, callback) {
		wx.ready(function() {
			wx.chooseWXPay({
				timestamp: jsApiParame.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
				nonceStr: jsApiParame.nonceStr, // 支付签名随机串，不长于 32 位
				package: jsApiParame.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
				signType: jsApiParame.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
				paySign: jsApiParame.paySign, // 支付签名
				success: function(res) {
					typeof callback == 'function' && callback(res);
				},
				fail: function(r) {
					console.log(r)
				}
			});
		})
	},

	/**
	 * 获取收货地址
	 * @param {Object} callback
	 */
	openAddress(callback) {
		wx.ready(function() {
			wx.openAddress({
				success: function(res) {
					typeof callback == 'function' && callback(res);
				},
				fail: (res) => {}
			});
		})
	},
	/**
	 * 分享给好友
	 * @param {Object} params
	 * @param {Object} callback
	 */
	setShareData(params, type, callback) {

		if (params.link.indexOf('?') != -1) {
			params.link += '&promotion_code=' + uni.getStorageSync('promotion_code') 
		} else {
			params.link += '?promotion_code=' + uni.getStorageSync('promotion_code') 
		}
		if (params.link.indexOf('tag=') == -1) {
			params.link +='&tag='+uni.getStorageSync('shoptag');
		}
		wx.ready(function() {
			// 自定义“分享给朋友”及“分享到QQ”按钮的分享内容
			if (type === 0) {
				wx.checkJsApi({
					jsApiList: ['updateAppMessageShareData'],
					success: (res) => {
						wx.updateAppMessageShareData({
							title: params.title || '', // 分享标题
							desc: params.desc || '', // 分享描述
							link: params.link || '', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
							imgUrl: params.imgUrl || '', // 分享图标
							success: function() {
								typeof callback == 'function' && callback(res);
							},
							fail: (err) => {
								console.log(err)
							}
						})
					}

				})
			} else {
				// 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容
				wx.checkJsApi({
					jsApiList: ['updateTimelineShareData'],
					success: (res) => {
						wx.updateTimelineShareData({
							title: params.title || '', // 分享标题
							link: params.link || '', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
							imgUrl: params.imgUrl || '', // 分享图标
							success: function() {
								typeof callback == 'function' && callback(res);
							},
							fail: (err) => {
								console.log(err)
							}
						})
					}
				})

			}

		});
	}
}
